import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
  /* 设置了默认子路由，则父级路由不需要设置name属性了。
  vue-router.esm.js?8c4f:16 [vue-router] Named Route 'Layout' has a default child route.
   When navigating to this named route (:to="{name: 'Layout'"),
   the default child route will not be rendered.
   Remove the name from this route and use the name of the default child route for named links instead.
  */
  {
    path: '/',
    // name: 'Layout',
    component: () => import(/* webpackChunkName: "index" */ '@/views/layout'),
    children: [
      {
        // path 为 ‘’ 会作为子路由默认渲染，
        path: '',
        name: 'Home',
        component: () => import(/* webpackChunkName: "index" */ '@/views/home')
      },
      {
        path: '/article',
        name: 'Article',
        component: () => import(/* webpackChunkName: "index" */ '@/views/article')
      },
      {
        path: '/image',
        name: 'Image',
        component: () => import(/* webpackChunkName: "index" */ '@/views/image')
      },
      {
        path: '/publish',
        name: 'Publish',
        component: () => import(/* webpackChunkName: "index" */ '@/views/publish')
      },
      {
        path: '/comment',
        name: 'Comment',
        component: () => import(/* webpackChunkName: "index" */ '@/views/comment')
      },
      {
        path: '/fans',
        name: 'Fans',
        component: () => import(/* webpackChunkName: "index" */ '@/views/fans')
      },
      {
        path: '/settings',
        name: 'Settings',
        component: () => import(/* webpackChunkName: "index" */ '@/views/settings')
      }
    ]
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import(/* webpackChunkName: "index" */ '@/views/login')
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach((to, before, next) => {
  const user = JSON.parse(localStorage.getItem('user'))
  if (to.path !== '/login') {
    if (user) {
      next()
    } else {
      next('/login')
    }
  } else {
    next()
  }
})

export default router
